package io.jft.doll.model.viewModel

import android.arch.lifecycle.LifecycleOwner
import com.g.base.api.ErrorCode
import com.g.base.api.ErrorException
import com.g.base.extend.mainIoSchedulers
import com.g.base.extend.resultNotNull
import com.g.base.extend.toObservable
import com.g.base.room.entity.UserEntity
import com.g.base.room.repository.NetworkBoundResult
import com.g.base.room.repository.ResultWarp
import com.g.base.viewModel.BaseViewModel
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.tencent.mm.opensdk.modelmsg.SendAuth
import io.jft.doll.api.WxApi
import io.jft.doll.api.apiProvider
import io.jft.doll.event.WX_APPSECRET
import io.jft.doll.event.WX_APP_ID
import io.jft.doll.room.repository.OauthRepository
import io.reactivex.Observable

/**
 * Created by G on 2017/11/13 0013.
 */
class OauthViewModel : BaseViewModel() {
    //用于界面数据绑定的Model
    private val oauthRepository by lazy { OauthRepository() }

    fun signIn(jsonObject: JsonObject): NetworkBoundResult<UserEntity?> = oauthRepository
            .signIn(jsonObject)

    fun signOut() = oauthRepository.signOut()

    fun getWxUserInfo(oauthResp: SendAuth.Resp, lifecycleOwner: LifecycleOwner): Observable<ResultWarp<UserEntity?>> {
        val wxApi = apiProvider.create(WxApi::class.java)
        return wxApi.getOauth2(WX_APP_ID, WX_APPSECRET, oauthResp.code, "authorization_code")
                .doOnError {
                    throw ErrorException(ErrorCode.WX_OAUTH, "获取微信登录秘钥失败", null)
                }
                .switchMap {
                    wxApi.getUserInfo(it.accessToken, it.openid)
                }
                .doOnError {
                    if (it is ErrorException && it.code == ErrorCode.WX_OAUTH)
                        throw ErrorException(ErrorCode.WX_OAUTH, "获取微信用户信息失败", null)
                }
                .switchMap {
                    signIn(Gson().toJsonTree(it).asJsonObject)
                            .resultNotNull()
                            .toObservable(lifecycleOwner)
                }
                .mainIoSchedulers()
    }
}